package net.gz01.wallet.web.controller.merch;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.common.ZOSearchCondition;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.model.MerchUser;
import net.gz01.wallet.web.model.TradeOrder;

public class TradeOrderController extends BaseController{

	public void search(){
		render("trade/tradeOrderList.html");
	}

	public void listJson() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		ZOSearchCondition sc = super.getSearchCondition();
		sc.put("merchCode", merchUser.getMerchCode());
		Page<TradeOrder> pageResult = TradeOrder.dao.search(sc);
		renderJson(new PageRespon(pageResult));
	}

	public void view() {
		setAttr("order", TradeOrder.dao.findById(getPara("id")));
		render("trade/tradeOrderView.html");
	}

	public void charts() {
		MerchUser merchUser = (MerchUser) getSession().getAttribute("loginMerchUser");
		String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		// select substring(createTime,12,2),count(*),sum(amount) from trade_order group by substring(createTime,12,2) order by substring(createTime,12,2)
		String sql = "select count(*) as count, sum(amount) as total from trade_order where merchCode=? and createTime like ?";
		//String sql = "select sum(amount) from trade_order where merchCode=? and createTime like ?";
		List<Record> records = new ArrayList<>();
		DecimalFormat df = new DecimalFormat("00");
		for (int i = 0; i < 24; i++) {
			Record record = Db.findFirst(sql, merchUser.getMerchCode(), date +" "+df.format(i)+"%");
			if (record.getInt("total") == null) {
				record.set("total", 0);
			}else {
				record.set("total", record.getInt("total")/100);			// 分转元，图表展示不需要百分百精确
			}
			records.add(record);
		}
		renderJson(records);
	}

}
